package com.eeGroup.controller;

import com.eeGroup.constants.Const;
import com.eeGroup.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class HomeController {

    static Logger logger = LoggerFactory.getLogger(HomeController.class);

    @RequestMapping(value = "/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "msg", required=false) String msg){
        ModelAndView model = new ModelAndView("loginPage");
        model.addObject("msg",msg);
        return model;
    }

    @RequestMapping(value = {"/main","/","/welcome"})
    public ModelAndView welcome(HttpSession session,
                                HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "msg", required=false) String msg){

        ModelAndView model = new ModelAndView("mainPage");
        model.addObject("msg",msg);
        return model;
    }


    @Autowired
    private LoginService loginService;

    @PostMapping("/doLogin")
    public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value ="password",required = false) String password){

        try {
            loginService.login(username,password);

            HttpSession session = request.getSession();
            session.setAttribute(Const.user, username);
            ModelAndView model = new ModelAndView("redirect:/main");
            return model;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            ModelAndView model = new ModelAndView("redirect:/login");
            model.addObject("msg",e.getMessage());
            return model;
        }
    }

    // 退出登录
    @RequestMapping("/logout")
    public ModelAndView logout(HttpSession session) {
        session.removeAttribute(Const.user);
        session.invalidate(); // 销毁会话
        return new ModelAndView("redirect:/login");
    }

    @RequestMapping("/test500")
    public String testError() {
        // 模拟一个未处理的异常
        throw new RuntimeException("这是一个模拟的服务器错误");
    }

}
